import { getContext, setContext } from './contextUtil'
import { Loader } from '../loader/Loader'

const loaderPrefix = 'loader'

function innerCreateLoader (loaderOrLoadFunc, loadParam) {
  if (loaderOrLoadFunc instanceof Loader) {
    return loaderOrLoadFunc
  }
  return new Loader(loaderOrLoadFunc, loadParam)
}

function contextKey (loaderName) {
  return `${loaderPrefix}.${loaderName}`
}

export function createLoader (loaderName, loaderOrLoadFunc = null, loadParams = null) {
  if (loaderOrLoadFunc == null) {
    loaderOrLoadFunc = loaderName
    loaderName = 'loader'
    loadParams = {}
  } else if (loaderName !== 'string') {
    loadParams = loaderOrLoadFunc || {}
    loaderOrLoadFunc = loaderName
    loaderName = 'loader'
  }
  const loader = innerCreateLoader(loaderOrLoadFunc, loadParams)
  setContext(contextKey(loaderName), loader)
  return loader
}

export function getLoader (loaderName = 'loader', route = '') {
  return getContext(contextKey(loaderName), route)
}